package stream

import (
	"github.com/kataras/iris/v12"
	"github.com/wutianze/nats.go"
	"gluenet/internal/glue-datasyncer/logs"
	"gluenet/modules/manager/stream/beats"
	"gluenet/modules/manager/stream/booter"
	"gluenet/modules/manager/stream/handler"
	"gluenet/modules/manager/stream/socket"
	"gluenet/pkg/apis"
	"gluenet/pkg/nets"
	v1 "gluenet/utils/rpc/labels"
	"strings"
)

var routers = [][2]interface{}{
	{v1.ControlManager + ":" + v1.TracePush, handler.Traces},
	{v1.ControlManager + ":" + v1.MetricsPush, handler.Metrics},
	{v1.ControlManager + ":" + v1.LogPush, logs.Logs},
}

var socketRouter = [][3]interface{}{
	{"GET", apis.SocketMetricsList, socket.MetricsList},
	{"GET", apis.SocketMetrics, socket.MetricsSocket},
	{"GET", apis.SocketMetricsTotal, socket.TotalMetricsSocket},

	{"GET", apis.SocketStatusList, socket.StatusList},
	{"GET", apis.SocketStatus, socket.StatusSocket},
	{"GET", apis.SocketStatusTotal, socket.TotalStatusSocket},

	{"GET", apis.InfoList, socket.InfosList},
	{"GET", apis.InfoGet, socket.InfosGet},
}

var bus_routers = [][]interface{}{
	// 后期流处理，暂时这样
	{strings.Join([]string{v1.ControlManager, apis.HeartBeat}, ":"), beats.HeartBeatNew},

	// 下发执行命令
	{apis.SchedulerEventResult, booter.BootIns},
}

func Register(rpc nets.GlueNets, app *iris.Application, ctx *apis.StorageContext) (map[string]*nats.Subscription, error) {
	fs := make(map[string]*nats.Subscription)
	for _, v := range routers {
		topic := v[0].(string)
		handfunc := v[1].(func(*apis.StorageContext))
		if sc, err := rpc.Subscribe(topic, func(m nets.NetContext) {
			ct := *ctx
			ct.RpcContext = &m
			handfunc(&ct)
		}); err != nil {
			return nil, err
		} else {
			fs[topic] = sc
		}
	}
	for _, v := range bus_routers {
		topic := v[0].(string)
		handfunc := v[1].(func(*apis.StorageContext))
		if sc, err := rpc.Subscribe(topic, func(m nets.NetContext) {
			ct := *ctx
			ct.RpcContext = &m
			handfunc(&ct)
		}); err != nil {
			return nil, err
		} else {
			fs[topic] = sc
		}
	}
	for _, v := range socketRouter {
		method := v[0].(string)
		route := v[1].(string)
		handfunc := v[2].(func(*apis.StorageContext))
		app.Handle(method, route, func(c iris.Context) {
			ct := *ctx
			ct.WebContext = c
			handfunc(&ct)
		})
	}

	return fs, nil
}
